import {createRouter, createWebHashHistory} from "vue-router";

import {useUserConfig} from "/@/stores/UserInfoConfig";
import {storeToRefs} from "pinia";
import {getMenus} from "/@router/menu";
import {useMessage} from "/@hooks/message";

// 初始化路由表数据
const init_menu = [
    {
        name:'MainIndex',
        path:'/',
        // @ts-ignore
        component:()=>import('/@/pages/home/MainIndex.vue'),
        children:[
            {name: 'UserInfo',showName: '用户信息',path: '/userInfo',index:2,component: () => import('/@/views/user/UserInfo.vue'), meta: {title: '用户信息',keepAlive: true}}
        ],
        redirect:'/index'
    },
    {
        name:'Login',
        path:'/auth/login',
        component:()=>import('/@/pages/login/Login.vue'),
        meta:{
            title:'登录',
            keepAlive:false
        }
    },
    {
        name:'Register',
        path:'/auth/register',
        component:()=>import('/@/pages/login/Register.vue'),
        meta:{
            title:'注册',
            keepAlive:false
        }
    }
]


// 静态路由
const router = createRouter({
    history : createWebHashHistory(),
    routes: [
        ...init_menu
    ]
})

/**
 * 初始化路由
 * 先将当前的路由还原为初始状态
 * 然后根据用户的权限动态添加路由
 */
export function initRouter() {
    // 先将当前的路由全部删除
    router.getRoutes().forEach((item) => {
        router.removeRoute(item.name as string)
    });
    // 将初始化路由添加到路由表中
    init_menu.forEach((item) => {
        router.addRoute(item)
    })
    // 根据用户角色获取最新的路由表
    const menus = getMenus();
    // 将最新的路由表添加到路由中(MainIndex的子路由)

    menus.forEach((item) => {
        router.addRoute('MainIndex',item)
    })
}


// 路由守卫
router.beforeEach((to, from, next):void => {

    const useUser = useUserConfig();
    const { userInfo } = storeToRefs(useUser);

    // 正则匹配 以 /demo 开头的路由 或者 /auth 开头的路由
    if (to.path.match(/^\/demo/) || to.path.match(/^\/auth/)) {
        next()
    }
    else {
        let token = userInfo.value.token;

        if (token === null) {
            next('/auth/login')
        } else {
            if(userInfo.value.is_active === false){
                useMessage().error('账号已被禁用，请联系管理员')
                next('/auth/login')
            }
            next()
        }
    }
})

export default router
